# run.py
import os
from datetime import timedelta
from flask import Flask, send_from_directory
from flask_jwt_extended import JWTManager
from app.routes.image_recognition import image_recognition_bp
from app.routes.upload import upload_bp
from app.routes.building import building_bp
from app.routes.auth import auth_bp
from app.routes.news import news_bp
from app.config import Config
from app.routes.ar_culture import ar_culture_bp
from app.routes.feedback_controller import feedback_bp
from app.routes.checkin import checkin_bp
from app.routes.user import user_bp  # 新增导入user_bp


app = Flask(__name__)

# 加载配置
app.config.from_object(Config)

# 配置上传文件夹 - 使用绝对路径
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'uploads')

# JWT配置
app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY', 'your-secret-key-change-this')
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=365)

# 初始化JWT
jwt = JWTManager(app)

# 注册蓝图
app.register_blueprint(image_recognition_bp)
app.register_blueprint(upload_bp)
app.register_blueprint(building_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(news_bp)
app.register_blueprint(ar_culture_bp)
app.register_blueprint(feedback_bp)
app.register_blueprint(checkin_bp)
app.register_blueprint(user_bp)  # 新增注册user_bp

# 添加静态文件路由
@app.route('/api/uploads/<path:filename>')
def uploaded_file(filename):
    """提供上传文件的访问路由"""
    upload_folder = app.config['UPLOAD_FOLDER']
    # 安全检查：确保请求的文件在上传目录内
    safe_path = os.path.join(upload_folder, filename)
    if not safe_path.startswith(upload_folder):
        return "访问受限", 403
        
    if not os.path.exists(safe_path):
        app.logger.error(f"文件不存在: {safe_path}")
        return "文件不存在", 404
        
    return send_from_directory(upload_folder, filename)

if __name__ == '__main__':
    # 启动前确保上传目录存在
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    app.run(host='0.0.0.0', port=app.config['PORT'], debug=app.config['DEBUG'])